import React from "react";
import { useI18n } from '@/utils/in18';
import CardsPC from "../cards_pc/CardsPC";

type SearchInputProps = {
    onCardClick?: (card: any) => void;
};

// 自定义下拉：用于控制弹窗背景与圆角
type SelectOption = { value: string; label: string };
type CustomSelectProps = {
    value: string | null;
    onChange: (val: string | null) => void;
    options: SelectOption[];
    placeholder: string;
    style?: React.CSSProperties;
    className?: string;
};

const CustomSelect: React.FC<CustomSelectProps> = ({ value, onChange, options, placeholder, style, className }) => {
    const [open, setOpen] = React.useState<boolean>(false);
    const [activeIndex, setActiveIndex] = React.useState<number>(-1);
    const wrapperRef = React.useRef<HTMLDivElement | null>(null);
    const [triggerColor, setTriggerColor] = React.useState<string>('#F472B6');

    const selected = React.useMemo(() => options.find(o => o.value === value) || null, [options, value]);

    React.useEffect(() => {
        const handleDocMouseDown = (e: MouseEvent) => {
            if (!wrapperRef.current) return;
            if (!wrapperRef.current.contains(e.target as Node)) {
                setOpen(false);
            }
        };
        document.addEventListener('mousedown', handleDocMouseDown);
        return () => { document.removeEventListener('mousedown', handleDocMouseDown); };
    }, []);

    const handleSelect = (val: string | null) => {
        onChange(val);
        setOpen(false);
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
        const all = [{ value: '', label: placeholder }, ...options];
        if (!open && (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown')) {
            setOpen(true);
            const currentIndex = Math.max(0, Math.min(all.length - 1, Math.max(0, options.findIndex(o => o.value === value)) + 1));
            setActiveIndex(currentIndex);
            e.preventDefault();
            return;
        }
        if (open) {
            if (e.key === 'Escape') {
                setOpen(false);
                e.preventDefault();
            } else if (e.key === 'ArrowDown') {
                setActiveIndex(prev => Math.min(prev + 1, all.length - 1));
                e.preventDefault();
            } else if (e.key === 'ArrowUp') {
                setActiveIndex(prev => Math.max(prev - 1, 0));
                e.preventDefault();
            } else if (e.key === 'Enter' || e.key === ' ') {
                const pick = all[activeIndex];
                if (pick) handleSelect(pick.value ? pick.value : null);
                e.preventDefault();
            }
        }
    };

    return (
        <div ref={wrapperRef} style={{ position: 'relative', width: '100%', ...(style || {}) }}>
            <button
                type="button"
                aria-haspopup="listbox"
                aria-expanded={open}
                onClick={() => setOpen(o => !o)}
                onKeyDown={handleKeyDown}
                className={className}
                onMouseEnter={() => {
                    try {
                        const dark = typeof document !== 'undefined' && (document.documentElement.classList.contains('dark') || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches));
                        setTriggerColor(dark ? '#fff' : '#000');
                    } catch (e) { setTriggerColor('#000'); }
                }}
                onMouseLeave={() => setTriggerColor('#F472B6')}
                style={{ width: '100%', textAlign: 'left', cursor: 'pointer', border: '1px solid #F472B6', color: triggerColor }}
            >
                <span className="font-medium">{selected ? selected.label : placeholder}</span>
            </button>
            {open && (
                <div
                    style={{
                        position: 'absolute',
                        top: '100%',
                        left: 0,
                        right: 0,
                        marginTop: 6,
                        background: '#18181B',
                        color: '#fff',
                        borderRadius: 8,
                        border: '1px solid #F472B6',
                        boxShadow: '0 8px 20px rgba(0,0,0,0.4)',
                        zIndex: 1000,
                        maxHeight: 260,
                        overflowY: 'auto',
                        padding: 6,
                    }}
                    role="listbox"
                >
                    <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                        {[{ value: '', label: placeholder }, ...options].map((opt, idx) => (
                            <li
                                key={`${opt.value}-${idx}`}
                                role="option"
                                aria-selected={(opt.value || null) === (value || '')}
                                onMouseEnter={() => setActiveIndex(idx)}
                                onMouseDown={(e) => e.preventDefault()}
                                onClick={() => handleSelect(opt.value ? opt.value : null)}
                                style={{
                                    padding: '8px 12px',
                                    cursor: 'pointer',
                                    color: '#fff',
                                    background: idx === activeIndex ? '#232327' : '#18181B',
                                    borderRadius: 6,
                                }}
                            >
                                {opt.label}
                            </li>
                        ))}
                    </ul>
                </div>
            )}
        </div>
    );
};

const SearchInput: React.FC<SearchInputProps> = ({ onCardClick }) => {
    const { t } = useI18n();

    // PC 顶部搜索栏本地状态
    const [pcKeyword, setPcKeyword] = React.useState<string>('');
    const [pcRace, setPcRace] = React.useState<string | null>(null);
    const [pcCategory, setPcCategory] = React.useState<string | null>(null);

    // placeholder 打字机效果相关
    const placeholderText = t('FilterSheet.search_placeholder') || '';
    const [displayedPlaceholder, setDisplayedPlaceholder] = React.useState<string>('');
    const [isTypingPlaceholder, setIsTypingPlaceholder] = React.useState<boolean>(true);
    const [isInputFocused, setIsInputFocused] = React.useState<boolean>(false);

    // 内部 filters，仅用于驱动 CardsPC 的请求
    const [filters, setFilters] = React.useState<{ keyword?: string; race?: string; category?: string } | null>(null);

    // 根据选择的类别动态决定标题
    const dreamWord = React.useMemo(() => {
        const isMale = pcCategory === 'real_male' || pcCategory === 'anime_male';
        return isMale ? 'Dream Guy' : 'Dream Girl';
    }, [pcCategory]);

    // PC 容器宽度与窄屏判断
    const [pcContainerStyle, setPcContainerStyle] = React.useState<React.CSSProperties>({ width: '70%', margin: '0 auto' });
    const [isNarrowPC, setIsNarrowPC] = React.useState<boolean>(false);
    React.useEffect(() => {
        const update = () => {
            try {
                const w = typeof window !== 'undefined' ? window.innerWidth : 1400;
                if (w < 1230) {
                    setPcContainerStyle({ width: '95%', margin: '0 auto' });
                } else {
                    setPcContainerStyle({ width: '70%', margin: '0 auto' });
                }
                setIsNarrowPC(w < 720);
            } catch (e) { }
        };
        update();
        window.addEventListener('resize', update, { passive: true } as any);
        return () => { try { window.removeEventListener('resize', update as any); } catch { } };
    }, []);

    // 交互：重置 / 确认 / 仅关键字搜索
    const handlePcReset = React.useCallback(() => {
        setPcKeyword('');
        setPcRace(null);
        setPcCategory(null);
        setFilters(null);
    }, []);

    const handlePcConfirm = React.useCallback(() => {
        const next = {
            keyword: pcKeyword.trim() || undefined,
            race: pcRace || undefined,
            category: pcCategory || undefined,
        } as any;
        setFilters(next);
    }, [pcKeyword, pcRace, pcCategory]);

    const handlePcSearchOnly = React.useCallback((val?: string) => {
        const q = String(val ?? pcKeyword ?? '').trim();
        if (!q) {
            try { console.log(t('FilterSheet.search_empty')); } catch (e) { }
            return;
        }
        setPcKeyword(q);
        setFilters((prev: any) => ({
            ...(prev || {}),
            keyword: q,
            race: pcRace || undefined,
            category: pcCategory || undefined,
        }));
    }, [pcKeyword, pcRace, pcCategory, t]);

    // 打字机效果：当输入为空且未聚焦时开启；当聚焦或有内容时停止并显示完整 placeholder
    React.useEffect(() => {
        let cancelled = false;
        let timer: number | undefined;

        if (isInputFocused || (pcKeyword && pcKeyword.trim().length > 0)) {
            setIsTypingPlaceholder(false);
            setDisplayedPlaceholder(placeholderText);
            return () => { cancelled = true; if (timer) { clearTimeout(timer); } };
        }

        setIsTypingPlaceholder(true);
        setDisplayedPlaceholder('');
        let idx = 0;

        const typeNext = () => {
            if (cancelled) return;
            if (idx <= placeholderText.length) {
                setDisplayedPlaceholder(placeholderText.slice(0, idx));
                idx += 1;
                timer = window.setTimeout(typeNext, 80) as unknown as number;
            } else {
                // 完成后短暂停顿，再重头开始
                timer = window.setTimeout(() => {
                    idx = 0;
                    setDisplayedPlaceholder('');
                    timer = window.setTimeout(typeNext, 500) as unknown as number;
                }, 1200) as unknown as number;
            }
        };

        // 初始延迟再开始打字
        timer = window.setTimeout(typeNext, 300) as unknown as number;

        return () => { cancelled = true; if (timer) { clearTimeout(timer); } };
    }, [isInputFocused, pcKeyword, placeholderText]);

    return (
        <div style={pcContainerStyle} className="hidden sm:block">
            {/* 标题版块 */}
            <div className="w-full text-center mt-8">
                <style>{`.gradient-text { background: linear-gradient(90deg, #EC4C94 0%, #FF9AC6 100%); -webkit-background-clip: text; background-clip: text; color: transparent; }`}</style>
                <p className="text-[2.5rem] font-extrabold">
                    <span className="text-[#180710] dark:text-[white]">Find Your </span>
                    <span className="gradient-text">{dreamWord}</span>
                </p>
            </div>

            {/* 搜索栏版块 */}
            <div className="mt-6">
                <style>{`.native-focus input:focus, .native-focus select:focus, .native-focus textarea:focus, .native-focus button:focus { box-shadow: none !important; outline: none !important; border-color: #EC4C94 !important; }
.select-trigger, .reset-btn { color: #F472B6; transition: color 120ms ease; }
.select-trigger:hover, .reset-btn:hover { color: #000 !important; }
.dark .select-trigger:hover, .dark .reset-btn:hover { color: #fff !important; }`}</style>
                <div className="native-focus w-full mt-4 mb-4 flex flex-wrap items-center gap-3">
                    {/* 关键字输入 */}
                    <div className={isNarrowPC ? 'w-full' : 'flex-1 min-w-[280px]'}>
                        <input
                            value={pcKeyword}
                            onChange={(e) => setPcKeyword(e.target.value)}
                            placeholder={displayedPlaceholder || ''}
                            onKeyDown={(e) => { if (e.key === 'Enter') handlePcSearchOnly(); }}
                            onFocus={() => { setIsInputFocused(true); }}
                            onBlur={() => { setIsInputFocused(false); }}
                            className="w-full bg-[white] dark:bg-[#18181A] dark:text-white border border-[#E5E7EB] dark:border-[#18181A] rounded px-3 py-2"
                        />
                    </div>

                    {/* 第二行：类别/种族/按钮 */}
                    {isNarrowPC ? (
                        <div className="w-full grid items-center gap-2" style={{ gridTemplateColumns: '2fr 2fr 1fr 1fr' }}>
                            {/* 类别选择 */}
                            <div className="w-full">
                                <CustomSelect
                                    value={pcCategory}
                                    onChange={(v) => setPcCategory(v)}
                                    placeholder={t('FilterSheet.gender_label')}
                                    options={[
                                        { value: 'real_male', label: t('FilterSheet.gender_real_male') },
                                        { value: 'real_female', label: t('FilterSheet.gender_real_female') },
                                        { value: 'anime_male', label: t('FilterSheet.gender_anime_male') },
                                        { value: 'anime_female', label: t('FilterSheet.gender_anime_female') },
                                    ]}
                                    className="select-trigger  w-full bg-white dark:bg-[#141414] dark:text-[#F472B6] border border-gray-300 dark:border-[#2a2a2a] rounded px-3 py-2"
                                />
                            </div>

                            {/* 种族选择 */}
                            <div className="w-full">
                                <CustomSelect
                                    value={pcRace}
                                    onChange={(v) => setPcRace(v)}
                                    placeholder={t('FilterSheet.species_label')}
                                    options={[
                                        { value: 'persion', label: t('FilterSheet.race_person') },
                                        { value: 'other', label: t('FilterSheet.race_other') },
                                    ]}
                                    className="select-trigger w-full cursor-pointer bg-white dark:bg-[#141414] dark:text-white border border-gray-300 dark:border-[#2a2a2a] rounded px-3 py-2"
                                />
                            </div>

                            {/* 按钮 */}
                            <button onClick={handlePcReset} style={{ width: '100%', cursor: 'pointer' }} className="reset-btn border border-gray-300 dark:border-[#2a2a2a] rounded px-3 py-2">
                                {t('FilterSheet.reset')}
                            </button>
                            <button type="button" onClick={handlePcConfirm} style={{ width: '100%', cursor: 'pointer' }} className="rounded px-3 py-2 border border-[#EC4C94] bg-[#EC4C94] text-white">
                                {t('FilterSheet.confirm')}
                            </button>
                        </div>
                    ) : (
                        <div className="flex items-center gap-2">
                            {/* 类别选择 */}
                            <div>
                                <CustomSelect
                                    value={pcCategory}
                                    onChange={(v) => setPcCategory(v)}
                                    placeholder={t('FilterSheet.gender_label')}
                                    options={[
                                        { value: 'real_male', label: t('FilterSheet.gender_real_male') },
                                        { value: 'real_female', label: t('FilterSheet.gender_real_female') },
                                        { value: 'anime_male', label: t('FilterSheet.gender_anime_male') },
                                        { value: 'anime_female', label: t('FilterSheet.gender_anime_female') },
                                    ]}
                                    style={{ minWidth: 160 }}
                                    className="select-trigger bg-white dark:bg-[#141414] dark:text-white border border-gray-300 dark:border-[#2a2a2a] rounded px-3 py-2"
                                />
                            </div>

                            {/* 种族选择 */}
                            <div>
                                <CustomSelect
                                    value={pcRace}
                                    onChange={(v) => setPcRace(v)}
                                    placeholder={t('FilterSheet.species_label')}
                                    options={[
                                        { value: 'persion', label: t('FilterSheet.race_person') },
                                        { value: 'other', label: t('FilterSheet.race_other') },
                                    ]}
                                    style={{ minWidth: 140 }}
                                    className="select-trigger bg-white dark:bg-[#141414] dark:text-white border border-gray-300 dark:border-[#2a2a2a] rounded px-3 py-2"
                                />
                            </div>

                            {/* 操作按钮 */}
                            <div className="flex items-center gap-2">
                                <button onClick={handlePcReset} style={{ cursor: 'pointer' }} className="reset-btn font-semibold border border-[#F472B6] dark:border-[#F472B6] rounded px-3 py-2">{t('FilterSheet.reset')}</button>
                                <button type="button" onClick={handlePcConfirm} style={{ cursor: 'pointer' }} className="rounded font-semibold px-3 py-2 bg-[#EC4C94] text-white">{t('FilterSheet.confirm')}</button>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* 数据列表：在子组件中发起（由 CardsPC 根据 filters 请求） */}
            <div>
                <CardsPC onCardClick={onCardClick} filters={filters || undefined} />
            </div>
        </div>
    );
};

export default SearchInput;


